﻿// <copyright file="UserExtension.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Provide extension feature to User.</summary>

namespace Sqwarea.Web.Extensions
{
    using System;
    using System.Collections.Generic;
    using System.Data.Linq;
    using System.Linq;
    using System.Web;
    using Persistence;

    /// <summary>
    /// Provides features to User
    /// </summary>
    public static class UserExtension
    {
        /// <summary>
        /// Checks whether or not user is dead
        /// </summary>
        /// <param name="user">The checked user</param>
        /// <returns>Death information</returns>
        public static bool IsDead(this User user)
        {
            return user.Id == 0;
        }

        /// <summary>
        /// Checks wether or not user is new
        /// </summary>
        /// <param name="user">The checked user</param>
        /// <returns>Novelty information</returns>
        public static bool IsNew(this User user)
        {
            return user.Id == -1;
        }

        /// <summary>
        /// Basic actions to do when a user is instanciated
        /// </summary>
        /// <param name="user">The checked user</param>
        public static void Initialize(this User user)
        {
            user.Id = -1;
            user.RemembranceSessions = new Dictionary<string, RemembranceSession>();
        }

        /// <summary>
        /// Checks wether or not remembrance key is valid
        /// And updates RemembranceSessions dictionnary
        /// </summary>
        /// <param name="user">The user checking</param>
        /// <param name="key">Remembrance key to check</param>
        /// <returns>Wether or not remembrance key is valid</returns>
        public static bool IsRemembranceKeyValid(this User user, string key)
        {
            foreach (var entry in user.RemembranceSessions)
            {
                if (entry.Value.CreationDate < DateTime.Now.AddMonths(-1))
                {
                    user.RemembranceSessions.Remove(entry.Key);
                }
            }

            return user.RemembranceSessions.ContainsKey(key);
        }

        /// <summary>
        /// Remembers user by adding a remembrance session associated with a key
        /// </summary>
        /// <param name="user">The user to remember</param>
        /// <param name="key">The remember key</param>
        public static void RememberMe(this User user, string key)
        {
            user.RemembranceSessions[key] = new RemembranceSession
            {
                CreationDate = DateTime.Now,
                Key = key
            };
        }
    }
}
